﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Xdocument = Xceed.Document.NET;
using Xwords = Xceed.Words.NET;


namespace ZhwangTool
{
    /// <summary>
    /// FindKeyWordUserControl.xaml 的交互逻辑
    /// </summary>
    public partial class FindKeyWordUserControl : UserControl
    {
        public FindKeyWordUserControl()
        {
            InitializeComponent();

            comBox1.SelectedIndex = 1;
        }




        private void ComBox1_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            listbox1.Items.Clear();

            textBox1.Text = string.Empty;

        }

        private void SelectFolderButton_Click(object sender, RoutedEventArgs e)
        {
            listbox1.Items.Clear();
            listbox2.Items.Clear();
            listbox3.Items.Clear();

            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();

            string path = string.Empty;

            if (folderBrowserDialog.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                return;

            }
            else
            {
                textBox1.Text = folderBrowserDialog.SelectedPath;

                path = folderBrowserDialog.SelectedPath;

            }

            #region 控制文件类型

            string p = "*";

            List<string> nameListInCurPath = new List<string>();

            nameListInCurPath = Tools.Getfiles(path, p, checkBox1.IsChecked);

            switch (comBox1.SelectedIndex)
            {
                case 0:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".txt")).ToList<string>();
                    break;
                case 1:

                    if (nameListInCurPath.Any(x => x.EndsWith(".doc")))
                    {
                        MessageBoxResult dialogResult = MessageBox.Show("程序无法解析.doc文件，请确认继续执行，还是转换格式后再次运行！", "所选的目录中包含后缀为.doc的文件", MessageBoxButton.YesNo);

                        if (dialogResult != MessageBoxResult.Yes)
                        {
                            return;
                        }
                        else
                        {
                            foreach (var item in nameListInCurPath.Where(x => x.EndsWith(".doc")).ToList<string>())
                            {

                                listbox3.Items.Add(item);
                            }

                        }

                    }
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".docx")).ToList<string>();

                    break;
                case 2:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".xls") || x.EndsWith(".pdf")).ToList<string>();
                    break;
                case 3:
                    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".txt") || x.EndsWith(".docx")).ToList<string>();
                    break;
                //case 4:
                //    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx")).ToList<string>();
                //    break;
                //case 5:
                //    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".pdf")).ToList<string>();
                //    break;
                //case 6:
                //    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".rar") || x.EndsWith(".zip") || x.EndsWith(".7z")).ToList<string>();
                //    break;
                //case 7:
                //    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".doc") || x.EndsWith(".docx") || x.EndsWith(".dwg") || x.EndsWith(".ppt") ||
                //     x.EndsWith(".pptx") || x.EndsWith(".xls") || x.EndsWith(".xlsx") || x.EndsWith("*.pdf")).ToList<string>();
                //    break;
                //case 8:
                //    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".jpg") || x.EndsWith(".JPG") || x.EndsWith(".BMP") || x.EndsWith(".bmp") || x.EndsWith(".png") || x.EndsWith(".PNG") ||
                //    x.EndsWith(".jpeg") || x.EndsWith(".JPEG")).ToList<string>();
                //    break;
                //case 9:
                //    nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(".bak")).ToList<string>();
                //    break;
                //case 10:
                //    //nameListInCurPath = nameListInCurPath.Where(x => x.EndsWith(textBox2.Text.Trim())).ToList<string>();

                //    string[] tagsTmp = textBox2.Text.Trim().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

                //    if (tagsTmp.Length > 0)
                //    {
                //        nameListInCurPath = nameListInCurPath.Where(x => tagsTmp.Any(tag => x.EndsWith(tag))).ToList<string>();
                //    }
                //    break;

                default:
                    break;
            }

            #endregion

            if (nameListInCurPath.Count >= 1)
            {
                listbox1.Items.Clear();

            }

            foreach (string item in nameListInCurPath)
            {
                listbox1.Items.Add(item);
            }



        }

        ObservableCollection<TxtWithLines> observableCollection = new ObservableCollection<TxtWithLines>();

        private void FindKeyWordButton_Click(object sender, RoutedEventArgs e)
        {


            observableCollection.Clear();

            foreach (string fileName in listbox1.Items)
            {
                if (!File.Exists(fileName))
                {
                    continue;
                }

                List<string> findLines = new List<string>();

                string words = containTag.Text;

                if (fileName.EndsWith(".txt"))
                {
                    bool b = false;

                    b = SearchKeywordInTxt(fileName, words, out findLines);

                    if (b)
                    {
                        observableCollection.Add(new TxtWithLines(fileName, findLines));

                    }
                }
                if (fileName.EndsWith(".docx"))
                {
                    bool b = false;

                    b = SearchKeywordInDocx(fileName, words, out findLines);




                    if (b)
                    {
                        observableCollection.Add(new TxtWithLines(fileName, findLines));

                    }

                }

            }

            dataGrid2.ItemsSource = observableCollection;


        }

        public static bool SearchKeywordInTxt(string filePath, string keyword, out List<string> outLines)
        {
            outLines = new List<string>();

            string[] tagS = keyword.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);


            // 打开文件流
            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                int lineNumber = 0;

                // 逐行读取文件
                while ((line = reader.ReadLine()) != null)
                {
                    lineNumber++;

                    // 检查当前行是否包含关键字
                    //兼容大小写搜索  原来的代码
                    //if (line.ToLower().Contains(keyword.ToLower()))
                    //{
                    //    outLines.Add(line);

                    //}

                    bool allWordsFound = true;

                    foreach (string word in tagS)
                    {
                        //判断是否是可以包容的词

                        string[] tagSTmp = word.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);

                        //包含可选字符情况

                        if (tagSTmp.Length > 0)
                        {
                            bool tmp = false;

                            foreach (var item in tagSTmp)
                            {

                                if (line.ToLower().Contains(item.ToLower()))
                                {
                                    tmp = true; // 如果发现某个单词在字符串中，标记为找到 

                                    break; // 跳出循环，因为已经知道不是所有单词都找到了
                                }

                            }

                            if (!tmp)
                            {
                                allWordsFound = false;
                                break;
                            }
                        }
                        else
                        {
                            if (!line.ToLower().Contains(word.ToLower()))
                            {
                                allWordsFound = false; // 如果发现某个单词不在字符串中，标记为未找到
                                                       //Console.WriteLine($"The word '{word}' was not found in the string.");
                                break; // 跳出循环，因为已经知道不是所有单词都找到了
                            }

                        }

                    }

                    if (allWordsFound)
                    {
                        outLines.Add(line);

                    }

                }
            }

            if (outLines.Count > 0)
            {
                return true;
            }
            else
            {
                return false;

            }

        }

        public static bool SearchKeywordInDocx(string filePath, string keyword, out List<string> outLines)
        {
            outLines = new List<string>();


            string[] tagS = keyword.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);


            //加载docx文件

            try
            {
                using (var document = Xwords.DocX.Load(filePath))
                {
                    // 遍历文档中的所有段落
                    //foreach (var paragraph in document.Paragraphs)
                    //{
                    //    // 打印每个段落的文本
                    //    //Console.WriteLine(paragraph.Text);

                    //    //MessageBox.Show(paragraph.Text);

                    //    string line = paragraph.Text;


                    //    if (ContainsAllKeywords(line,tagS))
                    //    {
                    //        outLines.Add(line);
                    //    }

                    //}

                    List<String> tmpOutLines = new List<string>();

                    Parallel.ForEach(document.Paragraphs, paragraph =>
                    {
                        string line = paragraph.Text;
                        if (ContainsAllKeywords(line, tagS))
                        {
                            lock (tmpOutLines)
                            {
                                tmpOutLines.Add(line);
                            }
                        }

                    });

                    foreach (var item in tmpOutLines)
                    {
                        outLines.Add(item);
                    }


                    //遍历文档中所有的表格
                    foreach (var table in document.Tables)
                    {

                        foreach (Xdocument.Row row in table.Rows)
                        {
                            foreach (Xdocument.Cell cell in row.Cells)
                            {

                                foreach (var para in cell.Paragraphs)
                                {

                                    string line = para.Text;

                                    if (ContainsAllKeywords(line, tagS))
                                    {
                                        outLines.Add(line);
                                    }

                                }
                            }

                        }

                    }

                }

            }
            catch (Exception)
            {
                MessageBox.Show(filePath + "文件被打开或者其他占用情况", "跳过 改文件的搜索！", MessageBoxButton.OK);

                return false;
                //throw;
            }


            if (outLines.Count > 0)
            {
                return true;
            }
            else
            {
                return false;

            }

        }



        /// <summary>
        /// 确定给定的字符串中是否包含所有的给定关键字，给定关键字包含可选和必选的情况
        /// </summary>
        /// <param name="text">给定的字符串</param>
        /// <param name="tagS">给定的关键字数组</param>
        /// <returns></returns>
        public static bool ContainsAllKeywords(string text, string[] tagS)
        {
            // 提前将文本转换为小写
            string lowerText = text.ToLower();

            foreach (string word in tagS)
            {
                string[] tagSTmp = word.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                if (tagSTmp.Length > 0)
                {
                    bool tmp = false;
                    foreach (var item in tagSTmp)
                    {
                        // 提前将可选词转换为小写
                        if (lowerText.Contains(item.ToLower()))
                        {
                            tmp = true;
                            break;
                        }
                    }
                    if (!tmp)
                    {
                        return false;
                    }
                }
                else
                {
                    // 提前将单个词转换为小写
                    if (!lowerText.Contains(word.ToLower()))
                    {
                        return false;
                    }
                }
            }
            return true;
        }


        private void ContainTag_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            //FindKeyWordButton_Click(sender,e);
        }

        private void DataGrid2_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            e.Row.Header = e.Row.GetIndex() + 1;
        }

        private void UserControl_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                if (listbox1.Items.Count > 0) // 你的条件
                {
                    FindKeyWordButton_Click(null, null); // 调用按钮的点击事件处理程序
                }
            }
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            #region 关键词预处理
           string keyword = containTag.Text;

            //string tagS = keyword.Replace(' ', '|').Trim('|');

            string pattern = @"\s+|\|+";

            string replacement = "|";

            string tagS = Regex.Replace(keyword, pattern, replacement);


            if (Regex.Replace(tagS, @"[.,;:。，；：？?]", string.Empty).Length < 2)
            {
                MessageBox.Show("有效关键字太少，请更正后再次运行");

                return;
            }

            #endregion
            //处理搜索出来的关键字，为控制红色显示做准备
 

            observableCollection.Clear();

            foreach (string fileName in listbox1.Items)
            {
                if (!File.Exists(fileName))
                {
                    continue;
                }

                List<string> findLines = new List<string>();

                string words = containTag.Text;

                if (fileName.EndsWith(".txt"))
                {
                    bool b = false;

                    b = SearchKeywordInTxt(fileName, words, out findLines);

                    if (b)
                    {
                        observableCollection.Add(new TxtWithLines(fileName, findLines));

                    }
                }
                if (fileName.EndsWith(".docx"))
                {
                    bool b = false;

                    b = SearchKeywordInDocx(fileName, words, out findLines);

                    if (b)
                    {
                        observableCollection.Add(new TxtWithLines(fileName, findLines));

                    }

                }

            }


            foreach (var item in observableCollection)
            {
                listbox2.Items.Add(item.Name);
            }

            table.RowGroups.Clear();

            for (int i = 0; i < observableCollection.Count; i++)
            {
                TxtWithLines txtWithLines = observableCollection[i];

                TableRowGroup rowGroup = new TableRowGroup();

                for (int j = 0; j < txtWithLines.FindStringList.Count; j++)
                {
                    TableRow row = new TableRow();

                    Paragraph paragraphA = new Paragraph
                    {
                        Margin = new Thickness(0, 10, 0, 10) // 上边距为 20 像素
                    };
                    Run runA = new Run(txtWithLines.Name);

                    paragraphA.Inlines.Add(runA);

                    TableCell cellA = new TableCell(paragraphA);

                    cellA.BorderBrush = Brushes.Black;

                    cellA.BorderThickness = new Thickness(2, 1, 0, 1);


                    //只有一组的情况
                    if (observableCollection.Count == 1)
                    {
                        if (txtWithLines.FindStringList.Count == 1)
                        {
                            cellA.BorderThickness = new Thickness(2, 2, 0.5, 2);
                        }
                        else
                        {
                            cellA.BorderThickness = new Thickness(2, 1, 0.5, 0.5);

                            //对特殊行进行更改
                            //txtWithLines.FindStringList.Count >1
                            if (j == 0)
                            {
                                cellA.BorderThickness = new Thickness(2, 2, 0.5, 0.5);
                            }
                            else if (j == txtWithLines.FindStringList.Count - 1)
                            {
                                cellA.BorderThickness = new Thickness(2, 1, 0.5, 2);
                            }
                        }
                    }
                    else
                    {
                        //全面设置边框，有特殊情况再处理特殊的

                        cellA.BorderThickness = new Thickness(2, 0.5, 0.5, 0.5);


                        if (j == 0)
                        {
                            cellA.BorderThickness = new Thickness(2, 1, 0.5, 0.5);
                        }
                        if (j == txtWithLines.FindStringList.Count - 1)
                        {
                            cellA.BorderThickness = new Thickness(2, 0.5, 0.5, 1);
                        }

                        //第一组  只控制首行
                        if (i == 0 && j == 0)
                        {
                            cellA.BorderThickness = new Thickness(2, 2, 0.5, 0.5);
                        }
                        //最后组 只控制尾行
                        if (i == observableCollection.Count - 1 && j == txtWithLines.FindStringList.Count - 1)
                        {
                            cellA.BorderThickness = new Thickness(2, 0.5, 0.5, 2);
                        }
                    }

                    row.Cells.Add(cellA);

                    Paragraph paragraph = new Paragraph
                    {
                        Margin = new Thickness(0, 10, 0, 10) // 上边距为 20 像素
                    };

                    paragraph.LineHeight = paragraph.FontSize * 1.5;

                    string tmpStr = txtWithLines.FindStringList[j];

                    List<string> runStrs = GetChildStrs(tagS, tmpStr);

                    foreach (var runStr in runStrs)
                    {
                        Run run = new Run(runStr);

                        if (tagS.Split('|').Contains(runStr))
                        {
                            run.Foreground = Brushes.Red;
                            run.FontWeight = FontWeights.Bold;
                            run.FontSize = paragraph.FontSize * 1.2;

                        }

                        paragraph.Inlines.Add(run);

                    }

                    TableCell cellB = new TableCell(paragraph);

                    cellB.BorderBrush = Brushes.Black;

                    //只有一组的情况
                    if (observableCollection.Count == 1)
                    {
                        if (txtWithLines.FindStringList.Count == 1)
                        {
                            cellB.BorderThickness = new Thickness(0.5, 2, 2, 2);
                        }
                        else
                        {
                            cellB.BorderThickness = new Thickness(0.5, 0.5, 2, 0.5);

                            //对特殊行进行更改
                            //txtWithLines.FindStringList.Count >1
                            if (j == 0)
                            {
                                cellB.BorderThickness = new Thickness(0.5, 2, 2, 0.5);
                            }
                            else if (j == txtWithLines.FindStringList.Count - 1)
                            {
                                cellB.BorderThickness = new Thickness(0.5, 0.5, 2, 2);
                            }
                        }
                    }
                    else
                    {
                        //全面设置边框，有特殊情况再处理特殊的
                        cellB.BorderThickness = new Thickness(0.5, 1, 2, 0.5);

                        if (j == 0)
                        {
                            cellB.BorderThickness = new Thickness(0.5, 1, 2, 0.5);
                        }
                        if (j == txtWithLines.FindStringList.Count - 1)
                        {
                            cellB.BorderThickness = new Thickness(0.5, 1, 2, 1);
                        }

                        //第一组  只控制首行
                        if (i == 0 && j == 0)
                        {

                            cellB.BorderThickness = new Thickness(0.5, 2, 2, 0.5);

                        }
                        //最后组 只控制尾行
                        if (i == observableCollection.Count - 1 && j == txtWithLines.FindStringList.Count - 1)
                        {
                            cellB.BorderThickness = new Thickness(0.5, 1, 2, 2);
                        }





                    }

                    row.Cells.Add(cellB);

                    rowGroup.Rows.Add(row);

                }

                table.RowGroups.Add(rowGroup);
                //table.RowGroups[0].Rows[0].Cells[0];

            }


            //与第二列无关
            for (int i = 0; i < table.RowGroups.Count; i++)
            {
                var rowGroup = table.RowGroups[i];

                if (i % 2 == 0)
                {
                    rowGroup.Background = Brushes.White;
                }
                else
                {
                    rowGroup.Background = Brushes.AliceBlue;
                }

                for (int j = 0; j < rowGroup.Rows.Count - 1; j++)
                {
                    TableRow row = rowGroup.Rows[j];

                    TableCell cell = row.Cells[0];

                    cell.BorderBrush = Brushes.Black;

                    cell.BorderThickness = new Thickness(2, 0.5, 0.5, 0.5);

                    if (table.RowGroups.Count == 1)
                    {
                        //cell.BorderBrush = Brushes.Red;

                        cell.BorderThickness = new Thickness(2, 2, 0.5, 2);
                    }
                    else
                    {
                        cell.BorderThickness = new Thickness(2, 1, 0.5, 1);

                        if (i == 0)
                        {
                            //cell.BorderBrush = Brushes.Cyan;

                            cell.BorderThickness = new Thickness(2, 2, 0.5, 0.5);
                        }
                        else if (i == table.RowGroups.Count - 1)
                        {
                            //cell.BorderBrush = Brushes.LightPink;

                            cell.BorderThickness = new Thickness(2, 0.5, 0.5, 2);
                        }
                    }

                }

            }

            foreach (var rowGroup in table.RowGroups)
            {
                int startCol = 0;

                int startRow = 0;

                int rowSpan = rowGroup.Rows.Count;

                int colSpan = 1;

                TableCell startCell = rowGroup.Rows[startRow].Cells[startCol];

                var contentType = startCell.Blocks.FirstBlock;

                // 设置 RowSpan 和 ColumnSpan
                startCell.RowSpan = rowSpan;

                startCell.ColumnSpan = colSpan;

                startCell.TextAlignment = TextAlignment.Left;


                // 删除被合并的单元格
                for (int row = startRow; row < startRow + rowSpan; row++)
                {
                    for (int col = startCol; col < startCol + colSpan; col++)
                    {
                        if (row == startRow && col == startCol) continue; // 跳过起始单元格

                        rowGroup.Rows[row].Cells.RemoveAt(col);
                    }
                }

            }

        }


        private void MergeCells(Table table, int startRow, int startCol, int rowSpan, int colSpan)
        {
            // 获取起始单元格
            TableCell startCell = table.RowGroups[0].Rows[startRow].Cells[startCol];

            // 设置 RowSpan 和 ColumnSpan
            startCell.RowSpan = rowSpan;
            startCell.ColumnSpan = colSpan;

            // 删除被合并的单元格
            for (int row = startRow; row < startRow + rowSpan; row++)
            {
                for (int col = startCol; col < startCol + colSpan; col++)
                {
                    if (row == startRow && col == startCol) continue; // 跳过起始单元格
                    table.RowGroups[0].Rows[row].Cells.RemoveAt(col);
                }
            }
        }

        public List<string> GetChildStrs(string keyword, string inputStr)
        {
            //keyword = "最美好 需要|须要 我们";
            string pattern = keyword.Replace(' ', '|').Trim('|');

            //inputStr = "这是一个示例文本，最美好的夜晚，其中部分文字将我们需要被高亮显示。这是一须要个示例文本，其中部分文字将被高亮显示。";

            //List<(string Match, int Index)> matchPositions = new List<(string, int)>();

            List<string> childStrs = new List<string>();

            int lastIndex = 0;

            foreach (Match match in Regex.Matches(inputStr, pattern))
            {
                // 添加匹配项之前的子字符串
                if (match.Index > lastIndex)
                {
                    childStrs.Add(inputStr.Substring(lastIndex, match.Index - lastIndex));
                }

                // 添加匹配项本身
                childStrs.Add(match.Value);
                //matchPositions.Add((match.Value, match.Index));

                // 更新 lastIndex
                lastIndex = match.Index + match.Length;
            }

            // 添加最后一个匹配项之后的子字符串
            if (lastIndex < inputStr.Length)
            {
                childStrs.Add(inputStr.Substring(lastIndex));
            }

            return childStrs;

        }

        private void InsertTable(int rows, int cols, bool autoSize)
        {
            // 创建一个 Table 对象
            Table table = new Table();
            table.BorderThickness = new Thickness(1);
            table.BorderBrush = Brushes.Black;

            // 计算每个单元格的宽度
            double cellWidth = (richTextBox.ActualWidth / cols) * 15; // 15 是一个比例因子，可以根据需要调整

            // 创建列定义
            for (int i = 0; i < 2; i++)
            {
                table.Columns.Add(new TableColumn());
            }

            TableRowGroup rowGroup = new TableRowGroup();

            // 创建行和单元格
            for (int i = 0; i < rows; i++)
            {
                TableRow row = new TableRow();
                for (int j = 0; j < cols; j++)
                {
                    TableCell cell = new TableCell(new Paragraph(new Run($"Cell {i + 1}, {j + 1}")));
                    row.Cells.Add(cell);
                }

                rowGroup.Rows.Add(row);
            }
            table.RowGroups.Add(rowGroup);
            // 将表格添加到 FlowDocument
            flowDocument.Blocks.Add(table);
        }

        private void Listbox1_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string file_Name = listbox1.SelectedItem as string;

            //MessageBox.Show(file_Name);

            //System.Diagnostics.Process.Start("Explorer", "/select," + file_Name);

            if (File.Exists(file_Name))
            {
                System.Diagnostics.Process.Start(file_Name);
            }

        }

        private void Listbox2_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string file_Name = listbox1.SelectedItem as string;

            //MessageBox.Show(file_Name);

            //System.Diagnostics.Process.Start("Explorer", "/select," + file_Name);

            if (File.Exists(file_Name))
            {
                System.Diagnostics.Process.Start(file_Name);
            }
        }

        private void Listbox3_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            string file_Name = listbox1.SelectedItem as string;

            //MessageBox.Show(file_Name);

            //System.Diagnostics.Process.Start("Explorer", "/select," + file_Name);

            if (File.Exists(file_Name))
            {
                System.Diagnostics.Process.Start(file_Name);
            }
        }

        private void Listbox1_Drop(object sender, DragEventArgs e)
        {
            // 检查是否有文件被拖入
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                // 获取拖入的文件路径数组
                string[] files = e.Data.GetData(DataFormats.FileDrop) as string[];

                if (files != null)
                {
                    // 遍历文件路径并添加到ListBox的Items中
                    foreach (string filePath in files)
                    {
                        if (listbox1.Items.Contains(filePath))
                        {
                            continue;
                        }
                        switch (comBox1.SelectedIndex)
                        {
                            case 0:
                                if (filePath.EndsWith(".txt"))
                                {
                                    listbox1.Items.Add(filePath);
                                }
                                break;
                            case 1:
                                if (filePath.EndsWith(".docx"))
                                {
                                    listbox1.Items.Add(filePath);
                                }
                                if (filePath.EndsWith(".doc"))
                                {
                                    if (listbox3.Items.Contains(filePath))
                                    {
                                        continue;
                                    }
                                    listbox3.Items.Add(filePath);
                                }
                                break;
                            case 2:
                                if (filePath.EndsWith(".pdf"))
                                {
                                    listbox1.Items.Add(filePath);
                                }
                                break;

                            case 3:
                                if (filePath.EndsWith(".docx"))
                                {
                                    listbox1.Items.Add(filePath);
                                }
                                if (filePath.EndsWith(".txt"))
                                {
                                    listbox1.Items.Add(filePath);
                                }

                                if (filePath.EndsWith(".doc"))
                                {
                                    if (listbox3.Items.Contains(filePath))
                                    {
                                        continue;
                                    }
                                    listbox3.Items.Add(filePath);
                                }
                                break;

                            default:
                                break;
                        }

                    }
                }
            }

       





        }
    }


    class TxtWithLines
    {
        string name;
        List<string> lineStrs;
        string findStr;
        string allContent;
        List<Color> colors;

        List<string> findStringList = new List<string>();




        public TxtWithLines(string _fileNmae, List<string> _lineStrs)
        {
            Name = _fileNmae;

            LineStrs = _lineStrs;

            string tmpStr = string.Empty;

            foreach (var item in _lineStrs)
            {

                findStringList.Add(item.TrimEnd('\r', '\n'));

                tmpStr = tmpStr + item + "\r\n";

            }

            findStr = tmpStr.TrimEnd('\r', '\n');

            //if (File.Exists(_fileNmae))
            //{
            //    using (StreamReader reader = new StreamReader(_fileNmae))
            //    {
            //        AllContent = reader.ReadToEnd();
            //    }
            //}

        }

        public string Name { get => name; set => name = value; }
        public List<string> LineStrs { get => lineStrs; set => lineStrs = value; }
        public string FindStr { get => findStr; set => findStr = value; }
        public string AllContent { get => allContent; set => allContent = value; }
        public List<Color> Colors { get => colors; set => colors = value; }
        public List<string> FindStringList { get => findStringList; set => findStringList = value; }
    }



}
